package com.yangjiayu.algorithm.binary_search;

import java.util.Arrays;

public class BinarySearch {

    //双指针
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        //排除特殊情况
        if(target < arr[left]  || target > arr[right]){
            return -1;
        }

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    //递归 增加搜索的上下界作为参数
    public static int binarySearch(int[] a, int key, int fromIndex, int toIndex) {
        // 基本判断，当起始位置大于结束位置时，直接返回-1，特殊情况超出最大最小值，直接返回-1
        if (key < a[fromIndex] || key > a[toIndex] || fromIndex > toIndex) {
            return -1;
        }
        //计算中间位置
        int mid = fromIndex + (toIndex - fromIndex) / 2;
        //判断中间位置和key的大小关系，更改搜索范围，递归调用
        if(key < a[mid]){
            return binarySearch(a, key, fromIndex, mid - 1);
        }else if(key > a[mid]){
            return binarySearch(a, key, mid + 1, toIndex);
        }else{
            return mid;
        }
    }

    public static void main(String[] args) {
//        Arrays.binarySearch() java本身有实现
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 5;
        System.out.println(binarySearch(arr, target));

        System.out.println(Arrays.binarySearch(arr, target));
        System.out.println(Arrays.binarySearch(arr, 0, arr.length, target));

    }
}
